import req from './axios.js';
let OSS = require('ali-oss');

const uploadImg = async (file, path, fileName) => {
  return await req
    .get(process.env.VUE_APP_BASE_URL + '/square/upload/webpub')
    .then(async (data) => {
      const isDev = process.env.NODE_ENV === 'development';
      const client = new OSS({
        region: 'oss-cn-shanghai',
        secure: true, // secure: 配合region使用，如果指定了secure为true，则使用HTTPS访问
        accessKeyId: data.accessKeyId,
        accessKeySecret: data.accessKeySecret,
        bucket: isDev ? 'jimu-dev-pub' : 'jimu-pub',
        stsToken: data.securityToken,
        endpoint: isDev ? '' : 'movtile.com',
      });
      let storeAs;
      if (path) {
        if (fileName) {
          storeAs = `/${path}/${fileName}`;
        } else {
          storeAs = `/${path}/` + getFileNameUUID();
        }
      } else {
        storeAs = '/other/' + getFileNameUUID();
      }

      if (file && file.name) {
        const _name = file.name.split('.');
        const suffix = (_name && _name[_name.length - 1]) || '';
        if (suffix) {
          storeAs = `${storeAs}.${suffix}`;
        }
      }
      // 文件路径
      try {
        return await client.put(storeAs, file);
      } catch (err) {
        console.error(err);
        throw err;
      }
    })
    .catch((err) => {
      console.error(err);
      throw err;
    });
};
export const getFileNameUUID = () => {
  function rx() {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
  }
  return `${+new Date()}${rx()}${rx()}`;
};
export default uploadImg;
